/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Utility;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Ruba
 */
public class SessionFactoryUtil {
    private static SessionFactory sessionFactory;
    //final
    private  Session session;
    public  SessionFactoryUtil(){
    }

    static {
        try {
          // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
           
        } catch (Throwable ex) {
           // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        
        return sessionFactory;
    }

    /** Opens a session and will not bind it to a session context
      * @return the session
    */
     public synchronized    Session getSession() {
         if(session==null||!session.isOpen())
      {
          System.out.println("Not Exist Create New...");
          return  SessionFactoryUtil.getSessionFactory().openSession();
      }
           System.out.println(" ..... Exist ......");
        return session;
    }

    
    
    /**
      * Returns a session from the session context. If there is no session in
      * the context it opens a session,
      * stores it in the context and returns it.
      * This factory is intended to be used with a hibernate.cfg.xml
      * including the following property <property
      * name="current_session_context_class">thread</property> This would return
      * the current open session or if this does not exist, will create a new
      * session
      * @return the session
    **/
    public  Session getCurrentSession() {
         if(session==null||!session.isOpen())
      {
          return  sessionFactory.getCurrentSession();
      }
        return session;
    }
/**
   * closes the session factory
*/
        public static void close(){
               if(sessionFactory != null)
                    sessionFactory.close();
               sessionFactory = null;
        }
}
